import random
import base64
import uuid
import string
from loguru import logger
from captcha.image import ImageCaptcha
from django_redis import get_redis_connection
from django.conf import settings


class __CaptchaService:
    __image_generator = ImageCaptcha(
        width=settings.CAPTCHA_IMAGE_SIZE[0], height=settings.CAPTCHA_IMAGE_SIZE[1]
    )

    def __init__(self):
        self.__redis = get_redis_connection(settings.CAPTCHA_CACHE)

    def generate_captcha(self):
        """生成验证码图片及UUID"""
        # 生成随机数字
        code = "".join(
            random.choices(
                string.ascii_letters + string.digits, k=settings.CAPTCHA_LENGTH
            )
        )

        # 生成唯一标识
        key = str(uuid.uuid4())

        # 存储到Redis
        self.__redis.setex(f"captcha:{key}", settings.CAPTCHA_TIMEOUT, code)

        # 生成图片
        image = self.__image_generator.generate(code)
        img_base64 = base64.b64encode(image.getvalue()).decode()

        return {"key": key, "image": f"data:image/png;base64,{img_base64}"}

    def validate_captcha(self, key, user_input):
        """验证码校验"""
        logger.debug(f"validate_captcha >>> key: {key} - code: {user_input}")
        stored_code = self.__redis.get(f"captcha:{key}")
        if not stored_code:
            return False

        # 删除已使用的验证码
        self.__redis.delete(f"captcha:{key}")
        return stored_code.decode().lower() == user_input.strip().lower()


captcha = __CaptchaService()
